/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wels.sample.slice;;

import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * GetFile to return the file from Raw File
 */
public class GetFile {
    /**
     * getFileFromRawFile
     *
     * @param filename The Filename of the document
     * @param rawFileEntry The rawFileEntry from Resource Manager
     * @param cacheDir The current Ability Context's CacheDir
     * @return file The actual file extracted from RawFile Descriptor.
     * @throws IOException Throws IOException incase of the FD is null
     */
    public static File getFileFromRawFile(String filename, RawFileEntry rawFileEntry, File cacheDir)
            throws IOException {
        byte[] buf = null;
        File file;
        FileOutputStream output = null;
        try {
            file = new File(cacheDir, filename);
            Resource resource = rawFileEntry.openRawFile();
            buf = new byte[(int) rawFileEntry.openRawFileDescriptor().getFileSize()];
            int bytesRead = resource.read(buf);
            if (bytesRead != buf.length) {
                throw new IOException("Asset read failed");
            }
            output = new FileOutputStream(file);
            output.write(buf, 0, bytesRead);

            return file;
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        } finally {
            output.close();
        }
    }
}
